/*
 *  Copyright 2015 The WebRTC Project Authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

package com.pine.rtc.org.component;

import android.widget.SeekBar;
import android.widget.TextView;

import com.pine.rtc.R;

import org.webrtc.CameraEnumerationAndroid.CaptureFormat;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Control capture format based on a seekbar listener.
 */
public class CaptureQualityController implements SeekBar.OnSeekBarChangeListener {
    // Prioritize framerate below this threshold and resolution above the threshold.
    private static final int FRAMERATE_THRESHOLD = 15;
    private final List<CaptureFormat> mFormats =
            Arrays.asList(new CaptureFormat(1280, 720, 0, 30000), new CaptureFormat(960, 540, 0, 30000),
                    new CaptureFormat(640, 480, 0, 30000), new CaptureFormat(480, 360, 0, 30000),
                    new CaptureFormat(320, 240, 0, 30000), new CaptureFormat(256, 144, 0, 30000));
    private TextView mCaptureFormatText;
    private CallFragment.OnCallEvents mCallEvents;
    private int mWidth = 0;
    private int mHeight = 0;
    private int mFramerate = 0;
    private double mTargetBandwidth = 0;
    private final Comparator<CaptureFormat> mCompareFormats = new Comparator<CaptureFormat>() {
        @Override
        public int compare(CaptureFormat first, CaptureFormat second) {
            int firstFps = calculateFramerate(mTargetBandwidth, first);
            int secondFps = calculateFramerate(mTargetBandwidth, second);

            if (firstFps >= FRAMERATE_THRESHOLD && secondFps >= FRAMERATE_THRESHOLD
                    || firstFps == secondFps) {
                // Compare resolution.
                return first.width * first.height - second.width * second.height;
            } else {
                // Compare fps.
                return firstFps - secondFps;
            }
        }
    };

    public CaptureQualityController(
            TextView captureFormatText, CallFragment.OnCallEvents callEvents) {
        this.mCaptureFormatText = captureFormatText;
        this.mCallEvents = callEvents;
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (progress == 0) {
            mWidth = 0;
            mHeight = 0;
            mFramerate = 0;
            mCaptureFormatText.setText(R.string.muted);
            return;
        }

        // Extract max bandwidth (in millipixels / second).
        long maxCaptureBandwidth = java.lang.Long.MIN_VALUE;
        for (CaptureFormat format : mFormats) {
            maxCaptureBandwidth =
                    Math.max(maxCaptureBandwidth, (long) format.width * format.height * format.framerate.max);
        }

        // Fraction between 0 and 1.
        double bandwidthFraction = (double) progress / 100.0;
        // Make a log-scale transformation, still between 0 and 1.
        final double kExpConstant = 3.0;
        bandwidthFraction =
                (Math.exp(kExpConstant * bandwidthFraction) - 1) / (Math.exp(kExpConstant) - 1);
        mTargetBandwidth = bandwidthFraction * maxCaptureBandwidth;

        // Choose the best format given a target bandwidth.
        final CaptureFormat bestFormat = Collections.max(mFormats, mCompareFormats);
        mWidth = bestFormat.width;
        mHeight = bestFormat.height;
        mFramerate = calculateFramerate(mTargetBandwidth, bestFormat);
        mCaptureFormatText.setText(
                String.format(mCaptureFormatText.getContext().getString(R.string.format_description), mWidth,
                        mHeight, mFramerate));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mCallEvents.onCaptureFormatChange(mWidth, mHeight, mFramerate);
    }

    // Return the highest frame rate possible based on bandwidth and format.
    private int calculateFramerate(double bandwidth, CaptureFormat format) {
        return (int) Math.round(
                Math.min(format.framerate.max, (int) Math.round(bandwidth / (format.width * format.height)))
                        / 1000.0);
    }
}
